<template>
  <!-- 字典管理 -->
  <div class="dictlist app-container">
    <el-row :gutter="0">
      <el-col :span="8">
        <div class="mainbox-left">

          <div class="box-card">
            <div style="margin-bottom:16px" class="filter-container">
              <el-input
                v-model.trim="dictTypeQuery.dictTypeName"
                maxlength="30"
                clearable
                class="filter-item limit"
                style="margin:0;"
                placeholder="请输入名称"
                @keyup.enter.native="handleDictTypeFilter"
              />
              <el-button
                type="primary"
                style="margin-left: 10px;"
                icon="el-icon-search"
                class="filter-item limit"
                @click="handleDictTypeFilter"
              >
                搜索
              </el-button>
            </div>
            <div>
              <el-button
                v-permission="['BASE_DICT_ADD_BUTTON']"
                size="mini"
                style="margin-bottom: 16px;"
                class="filter-item"
                @click="addDictType"
              >
                新增
              </el-button>
              <el-button
                v-permission="['BASE_DICT_UPDATE_BUTTON']"
                size="mini"
                style="margin-bottom: 16px;"
                class="filter-item"
                @click="editDictType"
              >
                修改
              </el-button>
              <el-button
                v-permission="['BASE_DICT_DEL_BUTTON']"
                type="danger"
                size="mini"
                style="margin-bottom: 16px;"
                class="filter-item"
                @click="deleteDictType"
              >
                删除
              </el-button>
            </div>
            <el-table
              ref="tableLeft"
              v-loading="dictTypeListLoading"
              :data="dictTypeList"
              border
              highlight-current-row
              style="width: 100%;"
              :header-cell-style="{background:'#F2F2f2'}"
              @row-click="clickDictType"
            >
              <template slot="empty">
                <p>{{ $store.getters.dataText }}</p>
              </template>
              <el-table-column
                align="center"
                width="70"
                type="index"
                label="序号"
                :index="table1_index"
              />
              <!-- prop="dictTypeSort" -->
              <el-table-column
                align="center"
                prop="dictTypeName"
                label="名称"
                show-overflow-tooltip
              />
              <el-table-column
                align="center"
                prop="dictTypeCode"
                label="编码"
                show-overflow-tooltip
              />
            </el-table>
            <!-- 分页器 -->
            <dt-pagination
              v-show="dictTypeTotal > 0"
              class="leftPagination"
              :pager-count="5"
              :total="dictTypeTotal"
              :page.sync="dictTypeQuery.pageNo"
              :limit.sync="dictTypeQuery.pageSize"
              @pagination="initDictType"
            />
          </div>
        </div>
        <dtDialog
          :title="dictTypeTextMap[dictTypeDialogStatus]"
          :close-on-click-modal="false"
          :visible.sync="dictTypeVisible"
          :is-loading="loading"
          destroy-on-close
          @closeDialog="resetDictTypeTemp"
          @comfirmBtn="dictTypeDialogStatus === 'create' ? submitDictType(): updateDictType()"
        >
          <el-form
            ref="dictTypeDataForm"
            slot="content"
            :rules="dictTypeRules"
            :model="dictTypeTemp"
            :disabled="isDisabled"
            label-position="right"
            label-width="82px"
            style="width: 100%"
          >
            <!-- :disabled="dictTypeTemp.dictTypeClass==2&&dictTypeDialogStatus=='update'" -->
            <el-form-item label="名称" prop="dictTypeName">
              <el-input v-model.trim="dictTypeTemp.dictTypeName" maxlength="30" show-word-limit
                        class="limit" />
            </el-form-item>
            <el-form-item label="系统字典" prop="dictTypeClass">
              <el-radio v-model.trim="dictTypeTemp.dictTypeClass" :label="1" @change="radioChange">业务类型</el-radio>
              <el-radio v-model.trim="dictTypeTemp.dictTypeClass" :label="2" @change="radioChange">
                系统类型(系统类型与代码中枚举关联，添加后不可修改)
              </el-radio>
            </el-form-item>
            <el-form-item label="类型编码" prop="dictTypeCode">
              <el-input v-model.trim="dictTypeTemp.dictTypeCode" :disabled="dictTypeDialogStatus === 'create'? false : true" maxlength="30"
                        show-word-limit class="limit" />
            </el-form-item>
            <el-form-item label="业务编码" prop="dictTypeBusCode">
              <el-input v-model.trim="dictTypeTemp.dictTypeBusCode" maxlength="30" show-word-limit
                        class="limit" />
            </el-form-item>
            <el-form-item label="排序" prop="dictTypeSort">
              <el-input v-model.trim="dictTypeTemp.dictTypeSort" :oninput="initPositiveInteger()" maxlength="8"
                        show-word-limit class="limit" />
            </el-form-item>
            <el-form-item label="备注" prop="dictTypeDesc">
              <el-input v-model.trim="dictTypeTemp.dictTypeDesc" maxlength="200" show-word-limit
                        type="textarea" class="limit" />
            </el-form-item>
          </el-form>
        </dtDialog>
      </el-col>
      <el-col :span="16" style="padding-left: 0px">
        <div class="mainbox">
          <!-- 顶部操作 -->
          <div class="filter-container">
            <el-form ref="filterFormRef" :inline="true" :model="filterForm">
              <el-form-item label="字典名称" prop="dictName">
                <el-input
                  v-model.trim="filterForm.dictName"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  placeholder="请输入内容"
                  @keyup.enter.native="handleFilter"
                />
              </el-form-item>
              <el-form-item label="字典编码" prop="dictCode">
                <el-input
                  v-model.trim="filterForm.dictCode"
                  class="filter-item limit"
                  maxlength="30"
                  clearable
                  placeholder="请输入内容"
                  @keyup.enter.native="handleFilter"
                />
              </el-form-item>
            </el-form>
            <div class="flex-1" />
            <el-button type="primary" @click="handleFilter">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
          <!-- 表格 -->
          <div class="table-container table-fullscreen">
            <div class="table-opt-container">
              <el-button v-permission="['BASE_DICT_ADDRIGHT_BUTTON']" :disabled="filterForm.dictTypeCode=='orgType'" class="filter-item"
                         type="primary" icon="el-icon-plus" @click="addDict">新增</el-button>
              <div class="flex-1" />
              <dt-dialog-column :columns="columns" @queryTable="getList" />
            </div>
            <el-table
              ref="table"
              v-loading="dictListLoading"
              :data="dictList"
              border
              highlight-current-row
              style="width: 100%;"
              :header-cell-style="headerCellStyle"
            >
              <template slot="empty">
                <p>{{ $store.getters.dataText }}</p>
              </template>
              <el-table-column
                fixed="left"
                type="index"
                label="序号"
                width="70"
                :index="table_index"
              />
              <el-table-column
                v-if="columns[0].show"
                key="dictName"
                prop="dictName"
                label="字典名称"
              />
              <el-table-column
                v-if="columns[1].show"
                key="dictCode"
                prop="dictCode"
                label="字典编码"
              />
              <el-table-column
                v-if="columns[2].show"
                key="dictSort"
                prop="dictSort"
                label="排序"
              />
              <el-table-column
                :key="Math.random()"
                fixed="right"
                label="操作"
                class-name="small-padding fixed-width"
                width="144"
              >
                <template slot-scope="{ row }">
                  <el-button
                    v-permission="['BASE_DICT_UPDATERIGHT_BUTTON']"
                    size="mini"
                    style="padding: 7px"
                    @click="editDict(row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    v-permission="['BASE_DICT_DELRIGHT_BUTTON']"
                    size="mini"
                    type="danger"
                    :disabled="filterForm.dictTypeCode=='orgType'"
                    @click="deleteDict(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <dt-pagination
              v-show="dictListTotal > 0"
              :total="dictListTotal"
              :page.sync="filterForm.pageNo"
              :limit.sync="filterForm.pageSize"
              @pagination="getList"
            />
          </div>

          <dtDialog
            :title="textMap[dialogStatus]"
            :close-on-click-modal="false"
            :visible.sync="dictVisible"
            :is-loading="loading"
            destroy-on-close
            @closeDialog="resetDictTemp"
            @comfirmBtn="dialogStatus === 'create' ? createData() : updateData()"
          >
            <el-form
              ref="dictDataForm"
              slot="content"
              :rules="dictRules"
              :model="dictTemp"
              label-position="right"
              label-width="82px"
              style="width: 100%;overflow-x: auto;"
            >
              <el-form-item label="字典名称" prop="dictName">
                <el-input v-model.trim="dictTemp.dictName" maxlength="30" show-word-limit
                          class="limit" />
              </el-form-item>
              <el-form-item label="字典简称" prop="dictShortName">
                <el-input v-model.trim="dictTemp.dictShortName" maxlength="30" show-word-limit
                          class="limit" />
              </el-form-item>
              <el-form-item label="字典编码" prop="dictCode">
                <el-input v-model.trim="dictTemp.dictCode" :disabled="dialogStatus=='update'" maxlength="30"
                          show-word-limit class="limit" />
              </el-form-item>
              <el-form-item label="编码简写" prop="dictShortCode">
                <el-input v-model.trim="dictTemp.dictShortCode" maxlength="30" show-word-limit
                          class="limit" />
              </el-form-item>
              <el-form-item label="排序" prop="dictSort">
                <el-input v-model.trim="dictTemp.dictSort" :oninput="initPositiveInteger()" show-word-limit
                          maxlength="8" class="limit" />
              </el-form-item>
            </el-form>
          </dtDialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import dictTypeApi from '@/framework/api/dictType'
import dictApi from '@/framework/api/dict'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'
import { positiveInteger } from '@/framework/utils/validate'

export default {
  name: 'BaseDict',
  mixins: [dialogColumn],
  data() {
    return {
      loading: false,
      dictTypeTotal: 0,
      dictListLength: 0,
      dictTypeListLength: 0,
      dictTypeQuery: {
        pageNo: 1,
        pageSize: 10,
        dictName: ''
      },
      dictTypeList: [],
      isDisabled: false,
      dictTypeDialogStatus: '',
      dictTypeTextMap: {
        update: '修改字典类型',
        create: '新增字典类型'
      },
      dictTypeListLoading: false,
      dictTypeVisible: false,
      dictTypeTemp: {
        dictTypeName: '',
        dictTypeClass: 1,
        dictTypeCode: '',
        dictTypeBusCode: '',
        dictTypeSort: '',
        dictTypeDesc: ''
      },
      dictTypeRules: {
        dictTypeName: [
          { required: true, message: '请输入名称', trigger: 'change' },
          { pattern: /^[^#@%&*¥$*]+$/, message: '不要输入特殊字符' }
        ],
        dictTypeClass: [
          { required: true, message: '请选择系统字典', trigger: 'change' }
        ],
        dictTypeCode: [
          { required: true, message: '请输入类型编码', trigger: 'change' }
          // { pattern: /^[A-Za-z0-9_]+$/, message: '请输入字母或数字' }
        ],
        dictTypeSort: [
          { required: true, message: '请输入排序', trigger: 'change' }
        ]
      },
      selectedDictType: {},
      filterForm: {
        dictName: '',
        dictCode: '',
        dictTypeCode: '',
        pageNo: 1,
        pageSize: 10
      },
      // 列信息
      columns: [
        { prop: 'dictName', label: '字典名称', show: true },
        { prop: 'dictCode', label: '字典编码', show: true },
        { prop: 'dictSort', label: '排序', show: true }
      ],
      dictListLoading: false,
      dictList: [],
      dictListTotal: 0,
      dialogStatus: '',
      textMap: {
        update: '修改字典数据',
        create: '新增字典数据'
      },
      dictTemp: {
        dictName: '',
        dictShortName: '',
        dictCode: '',
        dictShortCode: '',
        dictSort: ''
      },
      dictRules: {
        dictName: [
          { required: true, message: '请输入字典名称', trigger: 'change' },
          { required: false, pattern: /^[^#@%&*¥$*]+$/, message: '不要输入特殊字符' }
        ],
        dictCode: [
          { required: true, message: '请输入字典编码', trigger: 'change' }
          // { pattern: /^[A-Za-z0-9_]+$/, message: '请输入字母或数字' }
        ],
        dictSort: [
          { required: true, message: '请输入排序', trigger: 'change' }
        ]
      },
      dictVisible: false,
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      }
    }
  },
  watch: {
    selectedDictType(val, newval) {
      if (this.selectedDictType) {
        this.filterForm.dictTypeCode = this.selectedDictType.dictTypeCode
        this.filterForm.dictTypeId = this.selectedDictType.dictTypeId
        this.getList()
      }
    }
  },
  mounted() {
    this.handleDictTypeFilter()
  },
  methods: {
    // 校验排序规则
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    handleDictTypeFilter() {
      this.dictTypeQuery.pageNo = 1
      this.initDictType()
    },
    initDictType() {
      this.dictTypeListLoading = true
      dictTypeApi.page(this.dictTypeQuery).then((res) => {
        this.dictTypeList = res.data.rows
        this.dictTypeListLength = res.data.rows.length
        this.dictTypeTotal = res.data.totalRows
        this.selectedDictType = this.dictTypeList[0]
        this.dictTypeListLoading = false
        this.$nextTick(() => {
          this.$refs.tableLeft.setCurrentRow(this.dictTypeList[0])
        })
      })
    },
    clickDictType(row, column, event) {
      this.selectedDictType = row
    },
    addDictType() {
      this.isDisabled = false
      this.dictTypeDialogStatus = 'create'
      this.dictTypeVisible = true
      this.$nextTick(() => {
        this.$refs['dictTypeDataForm'].clearValidate()
      })
    },
    editDictType() {
      this.dictTypeDialogStatus = 'update'

      dictTypeApi.detail(this.selectedDictType.dictTypeId).then((res) => {
        this.dictTypeTemp = res.data
        this.dictTypeVisible = true
        this.$nextTick(() => {
          this.$refs['dictTypeDataForm'].clearValidate()

          if (this.dictTypeTemp.dictTypeClass === 2) {
            this.isDisabled = true
          } else {
            this.isDisabled = false
          }
        })
      })
    },
    radioChange(label) {
      this.isDisabled = false
    },
    resetDictTypeTemp() {
      this.dictTypeTemp = {
        dictTypeName: '',
        dictTypeClass: 1,
        dictTypeCode: '',
        dictTypeBusCode: '',
        dictTypeSort: '',
        dictTypeDesc: ''
      }
    },
    submitDictType() {
      this.$refs['dictTypeDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            dictTypeApi.add(this.dictTypeTemp).then((res) => {
              this.initDictType()
              this.dictTypeVisible = false
              this.$dtMessage({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    updateDictType() {
      this.$refs['dictTypeDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            dictTypeApi.edit(this.dictTypeTemp).then((res) => {
              this.initDictType()
              this.dictTypeVisible = false
              this.$dtMessage({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    deleteDictType() {
      if (this.selectedDictType.dictTypeClass === 2) {
        this.$dtMessage({
          type: 'error',
          message: '系统数据，不可删除!'
        })
        return
      }
      this.$dtMessageBox({ title: '提示', message: `确定要删除“${this.selectedDictType.dictTypeName}”吗?`, type: 'warning' }).then(() => {
        dictTypeApi.delete(this.selectedDictType).then((res) => {
          this.initDictType()
          this.$dtMessage({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    // 列表序号
    table_index(index) {
      return (this.filterForm.pageNo - 1) * this.filterForm.pageSize + index + 1
    },
    table1_index(index) {
      return (this.dictTypeQuery.pageNo - 1) * this.dictTypeQuery.pageSize + index + 1
    },
    // 获取页面列表
    getList() {
      this.dictListLoading = true
      dictApi.fetchPage(this.filterForm).then((res) => {
        this.dictList = res.data.rows
        this.dictListLength = res.data.rows.length
        this.dictListTotal = res.data.totalRows
        this.dictListLoading = false
      })
    },
    // 搜索
    handleFilter() {
      this.filterForm.pageNo = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.handleFilter()
    },
    resetDictTemp() {
      this.dictTemp = {
        configCode: '',
        configName: '',
        configValue: '',
        dictTypeCode: '',
        dictTypeId: '',
        remark: '',
        sysFlag: 'Y'
      }
    },
    addDict() {
      this.dialogStatus = 'create'
      this.dictVisible = true
      this.$nextTick(() => {
        this.$refs['dictDataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dictDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.dictTemp.dictTypeCode = this.selectedDictType.dictTypeCode
          this.dictTemp.dictTypeId = this.selectedDictType.dictTypeId
          try {
            dictApi.add(this.dictTemp).then((res) => {
              this.getList()
              this.dictVisible = false
              this.$dtMessage({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    editDict(row) {
      this.dialogStatus = 'update'
      dictApi.detail(row.dictId).then((res) => {
        this.dictTemp = res.data
        this.dictVisible = true
        this.$nextTick(() => {
          this.$refs['dictDataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dictDataForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            dictApi.edit(this.dictTemp).then((res) => {
              this.getList()
              this.dictVisible = false
              this.$dtMessage({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    deleteDict(row) {
      this.$dtMessageBox({ title: '提示', message: `确定要删除“${row.dictName}”吗?`, type: 'warning' }).then(() => {
        dictApi.delete(row).then((res) => {
          this.getList()
          this.$dtMessage({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        // 取消不做操作
      })
    }

  }
}
</script>
<style lang="scss" scoped>
::v-deep .leftPagination .el-pagination__sizes{
  display: none;
}
.filter-container{
  display: flex;
}
.dictlist .el-card {
    // height: calc(100vh - 135px);
  }
</style>
